package com.whsxt.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whsxt.constant.AreaConstant;
import com.whsxt.domain.Area;
import com.whsxt.mapper.AreaMapper;
import com.whsxt.service.AreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-18 11:29
 * @Description: ${Description}
 */
@Service
@Slf4j
@CacheConfig(cacheNames = "com.whsxt.service.impl.AreaServiceImpl")
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {

    @Autowired
    private AreaMapper areaMapper;


    /**
     * 查询地址
     *
     * @return
     */
    @Override
    @Cacheable(key = AreaConstant.AREA_PREFIX)
    public List<Area> list() {
        return areaMapper.selectList(null);
    }


    /**
     * 新增地址
     *
     * @param area
     * @return
     */
    @Override
    @CacheEvict(key = AreaConstant.AREA_PREFIX)
    public boolean save(Area area) {
        log.info("新增地址：{}", JSON.toJSONString(area));
        //拿到父id
        Long parentId = area.getParentId();
        if (parentId == null || parentId.equals(0L)) {
            //说明是第一级节点
            area.setLevel(1);
        } else {
            Area parent = areaMapper.selectById(parentId);
            if (parent == null) {
                log.info("父节点不存在");
                return false;
            }
            area.setLevel(parent.getLevel() + 1);
        }
        int insert = areaMapper.insert(area);
        return insert > 0;
    }


    @Override
    public List<Area> findAreaByPid(Long pid) {
        return areaMapper.selectList(new LambdaQueryWrapper<Area>()
                .eq(Area::getParentId, pid)
        );
    }
}
